package li.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import li.dao.AmountMapper;
import li.dao.CreditMapper;
import li.dto.Credit;
import li.dto.TbAmount;
import li.dto.TbUser;
import li.service.CreditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CreditServiceImpl implements CreditService {
    @Autowired
    AmountMapper am;

    @Autowired
    CreditMapper cm;

    @Override
    public TbAmount findUserAmount(TbUser user) {
        QueryWrapper q = new QueryWrapper();
        q.eq("account",user.getAccount());
        return am.selectOne(q);
    }

    @Override
    public TbAmount updateUserAmount(TbUser user) {
        QueryWrapper q = new QueryWrapper();
        q.eq("account",user.getAccount());
        TbAmount tbAmount = am.selectOne(q);

        if (tbAmount==null) {
            tbAmount = new TbAmount().setAccount(user.getAccount());
            am.insert(tbAmount);
        }else {
            tbAmount.setTotalamount(tbAmount.getTotalamount()+1000)
                    .setFreeamount(tbAmount.getFreeamount()+1000);
            am.updateById(tbAmount);
        }
        return tbAmount;
    }

    @Override
    public List<Credit> findUserCredits(TbUser user) {
        QueryWrapper q = new QueryWrapper();
        q.eq("consumer_id",user.getId());
        return cm.selectList(q);
    }
}
